package utils.animate
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	
	import utils.EnterFrameTimer;

	public class TweenLight extends EventDispatcher
	{
		private var timer:EnterFrameTimer;
		private var _target:DisplayObject;
		private var fx:Number;
		private var fy:Number;
		private var tx:Number;
		private var ty:Number;
		private var speedX:Number = 0;
		private var speedY:Number = 0;
		private var div:int = 3;
		private var ax:Number;
		private var ay:Number;
		private var _duration:Number = 60;
		private var increment:int;
		
		public function TweenLight()
		{
			initTimer();
		}
		
		public function get isTweening():Boolean
		{
			return timer.running;
		}
		
		public function get target():DisplayObject
		{
			return _target;
		}

		private function initTimer():void
		{
			timer = new EnterFrameTimer(20);
			timer.addEventListener(TimerEvent.TIMER,onTimer);
		}
		
		private function onTimer(event:TimerEvent):void
		{
			increment++;
		
			var d:Number = _duration - increment;
			target.x = tx - .5 * ax * d * d ;
			target.y = ty - .5 * ay * d * d ;
			if (increment >= _duration )
			{
				target.x = tx;
				target.y = ty;
				stop();
				dispatchEvent(new Event(Event.COMPLETE));
			}
		}
		
		public function set duration(v:Number):void
		{
			_duration = v * 50;
		}
		
		
		public function setTarget(target:DisplayObject,fx:Number,fy:Number,tx:Number,ty:Number):void
		{
			target.x = fx;
			target.y = fy;
			_target = target;
			this.fx = fx;
			this.fy = fy;
			this.tx = tx;
			this.ty = ty;
			
			var a:Number;
			var s:Number;
			
			
			s = Math.sqrt((tx - fx)*(tx - fx) + (ty - fy) * (ty - fy));
			
			if (s == 0)
			{
				a = 0;
				ax = 0;
				ay = 0;
				return;
			}
			a = 2 * s / (_duration * _duration); 
			var angle:Number = Math.atan2(ty - fy,tx - fx);
			ax = Math.cos(angle) * a;
			ay = Math.sin(angle) * a;
			
			increment = 0;
		}
		
		public function start():void
		{
			timer.start();
		}
		
		public function stop():void
		{
			timer.reset();
			
		}
		
		public function destroy():void
		{
			stop();
			timer.removeEventListener(TimerEvent.TIMER,onTimer);
			timer = null;
			_target = null;
		}
	}
}